package com.isyscore.controller.admin;


import com.isyscore.dto.PageInfoDto;
import com.isyscore.dto.sys.ListUserForm;
import com.isyscore.dto.sys.UserDto;
import com.isyscore.entity.admin.SysUser;
import com.isyscore.form.LoginForm;
import com.isyscore.service.admin.SysUserService;
import com.isyscore.utils.MesResult;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author LGL
 * @since 2024年10月25日
 */
@RestController
@RequestMapping("/api/sysUser")
@Tag(name = "用户管理", description = "用户管理相关接口")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/login")
    public MesResult login(@RequestBody LoginForm form) {
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(form.getUsername(), form.getPassword());
        try {
            currentUser.login(token);
            // 添加调试信息
            System.out.println("登录成功，Session ID: " + currentUser.getSession().getId());
            System.out.println("用户认证状态: " + currentUser.isAuthenticated());
            System.out.println("用户Principal: " + currentUser.getPrincipal());
            System.out.println("是否有system:user:view权限: " + currentUser.isPermitted("system:user:view"));
            return MesResult.success(null);
        } catch (AuthenticationException e) {
            return MesResult.error("用户名或密码错误！");
        }
    }
    @GetMapping("/getUserInfo")
    @Operation(summary = "获取用户信息")
    public MesResult getUserInfo() {
        return MesResult.success(SecurityUtils.getSubject().getPrincipal());
    }
    @PostMapping("/list")
    @RequiresPermissions("system:user:list")
    @Operation(summary = "获取用户列表")
    public MesResult list(@RequestBody ListUserForm form) {
        PageInfoDto<UserDto> list = sysUserService.listUsers(form);
        return MesResult.success(list);
    }



}

